package com.yang965.producer.kafka.manual;

import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;

public class CustomInterceptor implements ProducerInterceptor<String, String> {
    private volatile long success = 0;
    private volatile long failuer = 0;

    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) {
        // 修改信息，添加统一信息等
        String modifiedValue = "prefix1-" + producerRecord.value();
        return new ProducerRecord<>(producerRecord.topic(), producerRecord.partition(),
                producerRecord.timestamp(), producerRecord.key(), modifiedValue,
                producerRecord.headers());
    }

    @Override
    public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) {
        if (e == null) {
            success++;
        } else {
            failuer++;
        }
    }

    @Override
    public void close() {
        long l = success / (success + failuer);
        System.out.println("成功率：" + l);
    }

    @Override
    public void configure(Map<String, ?> map) {

    }
}
